package utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.File;

public class DatabaseUtil {
    private static String url;
    private static String username;
    private static String password;
    
    static {
        try {
            Properties prop = new Properties();
            String configPath = "config.properties";
            File configFile = new File(configPath);
            if (!configFile.exists()) {
                throw new RuntimeException("Cannot find config.properties");
            }
            
            prop.load(new FileInputStream(configFile));
            
            // 加载JDBC驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            
            // 获取数据库连接信息
            url = prop.getProperty("db.url");
            username = prop.getProperty("db.username");
            password = prop.getProperty("db.password");
            
            // 如果密码是加密的，使用 PasswordUtil 解密
            if (password != null && password.startsWith("ENC(")) {
                String encryptedPassword = password.substring(4, password.length() - 1);
                password = PasswordUtil.decrypt(encryptedPassword);
            }
            
            // 移除调试输出
            // System.out.println("Database URL: " + url);
            // System.out.println("Username: " + username);
            // System.out.println("Decrypted Password: " + password);
            
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to initialize database connection", e);
        }
    }
    
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }
    
    public static boolean testConnection() {
        try (Connection conn = getConnection()) {
            return conn != null && !conn.isClosed();
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
} 